﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SportsStore.Logging;
using SportsStore.Model;
using SportsStore.ServicesInterfaces;
using SportsStore.ServicesInterfaces.Interfaces;
using SportsStore.Web.Models.CartItem;

namespace SportsStore.Web.Controllers
{
    public class CartItemController : BaseController
    {
      private readonly ICartItemService _cartItemService;

      public CartItemController(ICartItemService cartItemService, ILogger logger)
        : base(logger)
      {
        _cartItemService = cartItemService;
      }

      public ActionResult Index()
      {
        var cartItemsViewModel = CartItemsViewModel();
        return View(cartItemsViewModel);
      }

      [HttpPost]
      public ActionResult AddToCart(int Id)
      {
        CartItem cartItem = new CartItem(this.HttpContext);
        _cartItemService.AddItem(Id, cartItem.CartId, 1);
        return RedirectToAction("Index", "CartItem");
      }

      [HttpPost]
      public ActionResult RemoveFromCart(int Id)
      {
        CartItem cartItem = new CartItem(this.HttpContext);
        _cartItemService.RemoveItem(Id, cartItem.CartId);
        return RedirectToAction("Index", "CartItem");
      }

      public ActionResult Summary()
      {
        var cartItemsViewModel = CartItemsViewModel();
        return PartialView(cartItemsViewModel);
      }

      private CartItemsViewModel CartItemsViewModel()
      {
        var cartItemsViewModel = new CartItemsViewModel();
        CartItem cartItem = new CartItem(this.HttpContext);

        var cartItems = _cartItemService.GetCartItems(cartItem.CartId);
        var cartTotal = _cartItemService.ComputeTotalValue(cartItem.CartId);

        cartItemsViewModel.AddCartItems(cartItems);
        cartItemsViewModel.CartTotal = cartTotal;
        return cartItemsViewModel;
      }
    }
}
